import cv2
import numpy as np

def nothing(x):
    pass

# trackbar
cv2.namedWindow('Trackbars')
cv2.createTrackbar('H_Min', 'Trackbars', 0, 255, nothing)
cv2.createTrackbar('H_Max', 'Trackbars', 255, 255, nothing)
cv2.createTrackbar('S_Min', 'Trackbars', 0, 255, nothing)
cv2.createTrackbar('S_Max', 'Trackbars', 255, 255, nothing)
cv2.createTrackbar('V_Min', 'Trackbars', 0, 255, nothing)
cv2.createTrackbar('V_Max', 'Trackbars', 255, 255, nothing)
cv2.createTrackbar('Light', 'Trackbars', 0, 200, nothing)

video = cv2.VideoCapture("real.avi")

STOP = False
tmp_frame = None
while True:
    if not STOP:
        ret, frame = video.read()
        tmp_frame = frame
    else:
        frame = tmp_frame
    # frame = cv2.flip(frame, 1)
    # frame = cv2.flip(frame, 0)
    gw = cv2.xphoto.createGrayworldWB()
    gw.setSaturationThreshold(1)
    frame = gw.balanceWhite(frame)

    h_min = cv2.getTrackbarPos('H_Min', 'Trackbars')
    h_max = cv2.getTrackbarPos('H_Max', 'Trackbars')
    s_min = cv2.getTrackbarPos('S_Min', 'Trackbars')
    s_max = cv2.getTrackbarPos('S_Max', 'Trackbars')
    v_min = cv2.getTrackbarPos('V_Min', 'Trackbars')
    v_max = cv2.getTrackbarPos('V_Max', 'Trackbars')

    lower = np.array([h_min, s_min, v_min])
    upper = np.array([h_max, s_max, v_max])
    mask = cv2.inRange(frame, lower, upper)
    result = cv2.bitwise_and(frame, frame, mask=mask)

    cv2.imshow('Trackbars', result)
    char = cv2.waitKey(1)

    if char & 0xFF == ord('q'):
        break
    elif char & 0xFF == ord(' '):
        STOP = not STOP